const User = require('../model/user/user')
const md5 = require('blueimp-md5')

const userController = {
   // 获取用户列表
  async getUserList(req, res) {
    let body = req.query
    let keyword = body.query //查询
    let reg = new RegExp(keyword, 'i')  //匹配
    let condition = {'nickname':{$regex:reg}} 
    let pagenum = parseInt(body.pagenum) ? parseInt(body.pagenum) :  1//当前第几页  
    let pagesize = parseInt(body.pagesize) //每页个数
    let sort = {'id':-1}            //字段排序
    let skipnum = (pagenum - 1) * pagesize  //跳过页数
    try {
       let total = await User.countDocuments({})
       await User.find(condition).skip(skipnum).limit(pagesize).sort(sort).exec((err,doc)=>{
         return  res.status(200).json({
                   status: 200,
                   list: doc,
                   sums:total,
                   message:'获取用户列表信息成功'
                 })            
       })
    } catch (error) {
        res.status(500).json({
            error_code: 1,
            message: '服务器错误'
      })
    }
  },
   // 增加用户
  async addUser(req,res) {
     let body = req.body
     body.password = md5(md5(body.password))
     try {
        await User.findOne({email: body.email}).exec((err,user) =>{
            if(user) {
               return res.status(201).json({
                   err_code: 1,
                   message: 'Email or nick name already exists!'
               })
            }  
            new User(body).save()
            res.status(200).json({
               err_code: 0,
               message: '添加用户成功！'  
           })
        })   
     } catch (error) {
        res.status(500).json({
            error_code: 1,
            message: '服务器错误'
        })
     }
  },
  // 删除用户
  async deleteUser(req,res) {
    let _id = req.params._id
    try {
      await User.findOne({_id : _id}).remove().exec((err,result) =>{
        if(result){
          return res.status(200).json({
            message: '删除成功！'
          })
        }
        res.status(201).json({
          message: '删除失败！'
        })
      })     
    } catch (error) {
        res.status(500).json({
            error_code: 1,
            message: '服务器错误'
      })
    }
  },
  // 编辑用户 
  async updataUser(req,res) {
    let _id = req.params._id
    let user = req.body
    try {
      await User.updateOne({_id:_id},{...user}).exec((err,result) =>{
        if(result) {
          return res.status(200).json({
            status:200,
            message:'修改成功'
          })
        }
        res.status(201).json({
          message: '修改失败！'
        })
      })  
    } catch (error) {
        res.status(500).json({
            error_code: 1,
            message: '服务器错误'
      })  
    }
  }
}

module.exports = userController